import React, { PureComponent } from 'react';
import { Table, Button, message, Pagination, Row, Col, Tabs, Popconfirm } from 'antd';
import services from '../../services/api';
import Modal from '../Modal/index';
import { AUDIT } from '../../utils/constant';
import './index.less';

export default class CommonList extends PureComponent {
  constructor() {
    super();
    this.api = '';
    this.tableParams = {};
    this.columns = [];
    this.tableClass = 'fixed';
    this.needOperateColumn = true;
    this.operatorWidth = '100px';
    this.AUDIT = AUDIT;
    this.editButton = (record) => {
      return (
        <Button size='small' type='link' onClick={this.edit.bind(this, record)}>
          编辑
        </Button>
      );
    };
    this.delButton = (record) => {
      return (
        <Popconfirm title='你确定要删除吗？' onConfirm={this.delete.bind(this, record)}>
          <Button size='small' type='link'>
            删除
          </Button>
        </Popconfirm>
      );
    };
    this.btnGroup = [this.editButton, this.delButton]; // 默认只有编辑、删除两个button, 扩展组件重写这个变量则可覆盖
  }

  edit(record, title) {
    title ? this.props.edit(record, title) : this.props.edit(record);
  }

  copy(record, title) {
    this.props.copy(record, title);
  }

  map(record) {
    this.props.map(record);
  }

  delete(record) {
    services[this.api].delete(this.getDeleteParam(record)).then((data) => {
      if (data.code === '0') {
        message.success(data.msg);
        this.props.queryList();
      } else {
        message.error(data.msg);
      }
    });
  }

  // 删除时的参数
  getDeleteParam = (record) => {
    return { id: record.id };
  };

  onChangePagination = (pageNumber) => {
    this.props.onChangePagination && this.props.onChangePagination(pageNumber, 'current');
  };

  onChangeSize = (current, size) => {
    this.props.onChangePagination && this.props.onChangePagination(size, 'size');
  };

  // 新增获取列的方法，用于特殊情况（异步表头）
  getColumn = () => {
    return [];
  };

  render() {
    this.defaultColumns = [
      {
        title: '操作',
        key: 'action',
        width: this.operatorWidth,
        fixed: 'right',
        render: (text, record, i) => {
          return (
            <div className='table-action'>
              {this.btnGroup &&
                this.btnGroup.map((fn, index) => {
                  return fn instanceof Object ? <span key={index}>{fn(record, i)}</span> : null;
                })}
            </div>
          );
        },
      },
    ];

    this.defaultColumns = this.needOperateColumn ? this.defaultColumns : [];
    const classN = this.tableClass ? this.tableClass : '';
    const customColumns = this.getColumn().map((it) => {
      return {
        ...it,
        width: it.width ? it.width : 100,
      };
    });
    const colums = this.props.columns
      ? [...this.props.columns, ...this.columns, ...this.getColumn()]
      : [...this.columns, ...this.getColumn()];
    // 如果有自定义列，则展示筛选后的列
    const filterColumns = this.props.defaultColumns
      ? this.props.defaultColumns.length > 0
        ? colums.filter((item) => {
            return item && this.props.defaultColumns.includes(item.key);
          })
        : colums
      : colums;
    const finnalyColumns = [...filterColumns, ...this.defaultColumns]; // 最终渲染的列
    const newOtherParams = {
      rowKey: 'id',
      scroll: {
        x: finnalyColumns.length > 9 ? 1300 : false,
      },
      ...this.tableParams,
      dataSource: this.props.records,
    };
    const { showSizeChanger = true } = this.props;
    const tableCreate = () => (
      <>
        <Table
          className={classN}
          loading={this.props.loading}
          columns={finnalyColumns}
          pagination={!this.props.current}
          {...newOtherParams}
          rowKey={this.props.rowKey || ''}
          scroll={this.props.scroll || {}}
          rowSelection={this.props.rowSelection}
          expandedRowRender={this.props.expandedRowRender}
          onChange={this.props.onChange}
        />
        {this.props.current && this.props.total > 0 && (
          <Row
            type='flex'
            justify={this.props.renderOtherParams ? 'space-between' : 'end'}
            align='middle'
            style={{ margin: '20px 0 0 0' }}
          >
            {this.props.renderOtherParams && <Col span={8}>{this.props.renderOtherParams()}</Col>}
            <Col>
              <Pagination
                showQuickJumper={!this.props.notQuickJumper}
                current={this.props.current}
                pageSize={this.props.size}
                total={this.props.total}
                showTotal={(total) => {
                  return this.props.exceededNum === 1 ? `总共 ${total}+ 条` : `总共 ${total} 条`;
                }}
                onChange={this.onChangePagination}
                showSizeChanger={showSizeChanger}
                pageSizeOptions={['5', '10', '15', '20']}
                onShowSizeChange={this.onChangeSize}
                style={{ textAlign: 'right' }}
                size={this.props.paginationSize || ''}
              />
            </Col>
          </Row>
        )}
      </>
    );
    return (
      <div>
        {this.props.tabs ? (
          <Tabs defaultActiveKey={this.props.tabs[0].key} onChange={this.props.tabChange}>
            {this.props.tabs.map((item) => (
              <Tabs.TabPane tab={item.name} key={item.key}>
                {this.props.records ? tableCreate() : '暂无数据'}
              </Tabs.TabPane>
            ))}
          </Tabs>
        ) : (
          <>{this.props.records ? tableCreate() : '暂无数据'}</>
        )}
      </div>
    );
  }
}
